import {
  request
} from '../../request/index'
import regeneratorRuntime from '../../lib/runtime/runtime'
import PubSub from 'pubsub-js'

Page({

  data: {
    tabs: [{
        id: 0,
        value: "歌曲",
        isActive: true
      },
      {
        id: 1,
        value: "视频",
        isActive: false
      },
    ],
    recentPlayList: [],
    index:0,
    videoList:[],
    isTriggered:false
  },
  userParams: {
    uid: "",
    type: 0
  },

  onLoad: function (options) {
    this.userParams.uid = options.uid
    if (options.uid) {
      this.getRecentPlayLisy()
      this.getRencentVideo()
    }

    //订阅来自详情页的发布消息
    PubSub.subscribe('switchType',(msg,type)=>{
      let {recentPlayList , index} = this.data
      if(type === 'pre'){ //上一首
        (index === 0) && (index = recentPlayList.length)
        index -= 1
      }else{ //  下一首
        (index === recentPlayList.length-1) && (index = -1)
        index += 1
      }

      this.setData({
        index
      })
      let musicId = recentPlayList[index].song.id

      //发布消息
      PubSub.publish("musicId",musicId)

    })
  },
  //点击切换tab
  handleTabsItemChange(e) {
    const {
      index
    } = e.detail

    let {
      tabs
    } = this.data

    tabs.forEach((v, i) => i === index ? v.isActive = true : v.isActive = false)

    this.setData({
      tabs
    })
  },
  //获取最近音乐播放记录
  async getRecentPlayLisy() {
    let {
      data
    } = await request({
      url: "/user/record",
      data: this.userParams
    })
    this.setData({
      recentPlayList: data.allData
    })
  },
 //去歌曲详情页面
  toDetail(e){
    let id = e.currentTarget.dataset.id
    let index = e.currentTarget.dataset.index

    this.setData({
      index
    })
    wx.navigateTo({
      url: '/pages/songDetail/index?id=' + id
    });
  },

  //获取最近视频播放
  async getRencentVideo(){
    let {data:{data}} = await request({url:"/playlist/video/recent"})

    this.setData({
      videoList:data.videos
    })
  },

    //下拉刷新
    handleRefresher() {
      this.getVideoList(this.data.navId)
    },
  
    onShareAppMessage:function({from}){
      return{
        title:"神级现场",
        page:"/pages/video/index",
      }
      
    }

})